using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlayerController : MonoBehaviour {
	
    public float movementSpeed = 3f;
	public float jumpSpeed = 4f;
	private float verticalSpeed = 0.0f;
	private float jumpTime;
    public float gravity = 20.0f;
    CharacterState _characterState;

    public AnimationClip idleAnimation;
    public AnimationClip runAnimation;
    private Animation _animation;
    public float runMaxAnimationSpeed = 1.0f;

    private PlayerCharacter myPlayer;

    enum CharacterState {
        idle = 0,
        run = 1
    }

    private CharacterController controller;
    private Vector3 moveDirection = Vector3.zero;

    public Transform player;
	public Transform attackRange;

    void Awake() {
        controller = GetComponent<CharacterController>();
        _animation = GetComponent<Animation>();
        myPlayer = GetComponent<PlayerCharacter>();
        if(!_animation)
            Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
        if(!idleAnimation) {
            _animation = null;
            Debug.Log("No idle animation found. Turning off animations.");
        }
        if(!runAnimation) {
            _animation = null;
            Debug.Log("No run animation found. Turning off animations.");
        }
    }

    void Update() {
        if(networkView.isMine) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
			moveDirection += new Vector3(0, verticalSpeed, 0).normalized;
			moveDirection *= movementSpeed;
			if(controller.isGrounded){
				verticalSpeed = 0.0f;
            	if(Input.GetButton("Jump")){
                	verticalSpeed = jumpSpeed;
					jumpTime = Time.time;
				}
			}
			else{
				verticalSpeed -= gravity * Time.deltaTime;
			}

            networkView.RPC("moveTo", RPCMode.All, moveDirection);

            if(IsMoving()) {
                _characterState = CharacterState.run;
                networkView.RPC("playerDirection", RPCMode.All, new Vector3(moveDirection.x, 0, moveDirection.z));
                networkView.RPC("setAnimationState", RPCMode.All, _characterState.ToString());
            }
            else {
                _characterState = CharacterState.idle;
                networkView.RPC("setAnimationState", RPCMode.All, _characterState.ToString());
            }
        }
    }
	
    [RPC]
    void moveTo(Vector3 destiny) {
        controller.Move(destiny * Time.deltaTime);
    }

    [RPC]
    void setAnimationState(string animation) {
        _animation.CrossFade(animation);
    }

    [RPC]
    void playerDirection(Vector3 playerTargetDirection) {
        transform.rotation = Quaternion.LookRotation(playerTargetDirection);
    }

    bool IsMoving(){
        return (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0);
    }
}
